import os
import sys
from typing import Optional

from core.client import APIClient
from core.auth import AuthManager
from lib.course_service import CourseService
from lib.video_service import VideoService
from lib.download_service import DownloadService
from lib.logger import Logger
from lib.input_handler import InputHandler
from config.settings import Config


class QiHangApp:
    """主应用类，整合所有功能"""
    
    def __init__(self, work_dir: Optional[str] = None, m3u8_path: Optional[str] = None, 
                 save_course_info: Optional[bool] = None):
        self.work_dir = work_dir or Config.DEFAULT_WORK_DIR
        self.m3u8_path = m3u8_path or Config.DEFAULT_M3U8_PATH
        self.save_course_info = save_course_info or Config.SAVE_CONFIG['save_course_info']
        
        # 初始化服务
        self.client = APIClient(Config.DEFAULT_HEADERS)
        self.auth = AuthManager(self.client)
        self.course_service = CourseService(self.client)
        self.video_service = VideoService(self.client)
        self.download_service = DownloadService(self.client)
        
        # 初始化日志
        self.logger = Logger()
        
        # 设置控制台编码
        os.system('chcp 65001')
    
    def run(self, account: Optional[str] = None, password: Optional[str] = None):
        """运行主程序"""
        try:
            self._print_banner()
            
            # 获取登录凭据
            if account and password:
                self.logger.info(f"使用提供的账号登录: {account}")
            else:
                account, password = InputHandler.get_credentials()
            
            # 登录
            token = self.auth.login(account, password)
            self.client.update_headers({'authorization': token})
            
            # 获取课程列表
            self.logger.info("获取课程列表...")
            courses = self.course_service.get_course_list()
            
            if not courses:
                self.logger.warning("没有找到可用的课程")
                return
            
            # 选择课程
            selected_index = InputHandler.select_course(courses)
            selected_course = courses[selected_index]
            
            self.logger.info(f"开始处理课程: {selected_course['productName']}")
            
            # 获取视频信息
            self.logger.info("获取视频列表...")
            video_list = self.course_service.extract_video_info(
                selected_course['productCurriculumId']
            )
            
            if not video_list:
                self.logger.warning("没有找到可下载的视频")
                return
            
            self.logger.info(f"找到 {len(video_list)} 个视频")
            
            # 准备课程信息
            course_info = {
                'courseNodes': [],
                'productName': selected_course['productName'],
                'userProductId': selected_course['userProductId'],
                'productCurriculumId': selected_course['productCurriculumId']
            }
            
            # 下载所有视频
            for name, vid in video_list:
                self.logger.info(f"处理视频: {name}")
                
                # 获取视频URL
                url = self.video_service.get_video_url(vid, selected_course['userProductId'])
                
                if not url:
                    self.logger.warning(f"无法获取视频URL: {name}")
                    continue
                
                # 记录视频信息
                course_info['courseNodes'].append({
                    'name': name,
                    'vid': vid,
                    'url': url
                })
                
                # 下载视频
                self.download_service.download_video(name, url, self.work_dir, self.m3u8_path)
            
            # 根据配置决定是否保存课程信息
            if self.save_course_info:
                self.logger.info("正在保存课程信息...")
                self.course_service.save_course_info(
                    selected_course['productName'],
                    selected_course['productCurriculumId'],
                    selected_course['userProductId'],
                    course_info
                )
                self.logger.info(f"课程信息已保存到: {selected_course['productName']}_courseInfo.json")
            else:
                self.logger.info("跳过保存课程信息（可在配置中启用）")
            
            # 清理临时日志目录
            self.logger.info("开始清理临时日志...")
            self.download_service.cleanup_logs()
            
            self.logger.info("所有任务完成！")
            
        except KeyboardInterrupt:
            self.logger.info("用户中断操作")
        except Exception as e:
            self.logger.error(f"程序运行出错: {str(e)}")
            raise
    
    def _print_banner(self):
        """打印程序横幅"""
        banner = """
╔═══════════════════════════════════════════════════════════════════════╗
║                           启航视频下载器 v3.1.2                          ║
║                                                                       ║
║  作者：MySheep                                                         ║
║  项目地址：https://gitee.com/mysheep0/QiHangVideo_Download              ║
║  文章地址：https://blog.csdn.net/m0_60082046/article/details/144569851  ║
╚═══════════════════════════════════════════════════════════════════════╝
        """
        print(banner)
        print(f"\033[1;31m视频将保存在: {self.work_dir}\033[0m")
